<?php
/*
  +----------------------------------------------------------------------+
  | UCLibVisitor.php                                                          |
  +----------------------------------------------------------------------+
  | Copyright (c) 2010 snda.com - Web Development Center                 |
  +----------------------------------------------------------------------+
  | 访客记录 engine                                                      |
  +----------------------------------------------------------------------+
  | Authors: Terry <leo9127@163.com>                                     |
  +----------------------------------------------------------------------+
*/

require_once(dirname(__FILE__).'/../config/comment/UCConfComment.php');
require_once(dirname(__FILE__).'/../libraries/UCLibPDOFactory.php');
require_once(dirname(__FILE__).'/../libraries/UCLibCache.php');

class UCLibVisitor{
	
	//生成CACHE KEY
	static function _visitorKey($user,$type='visitors',$exp=''){
	  $user	= strtolower(trim($user));
	  $type	= strtolower(trim($type));
	  if($type != 'visitors' && $type != 'browse'){
	    return false;
	  }
		$key = md5("visitor_".$user."_".$type."_visitorKey_".$exp);
		return $key;
	}
	
	/**
	 * 将用户访问数据写入DB并且更新CACHE
	 * @param $user: 被访问用户ID
	 * @param $visitor: 访问用户ID
	 * @int  $num: CACHE中记录数量
	 */
	 
	 public static function writeVisitor($user,$visitor){
	  $user	= strtolower(trim($user));
	  $visitor	= strtolower(trim($visitor));
	  if($user == $visitor){
	    return;
	  }
	  $num=30;
	  $num = intval($num);
	  if(!$user || !$visitor || !$num){
	    return;
	  }
	  //判断用户这次登录是否被统计过
	  //$statistics = $_COOKIE[strtoupper('HOME_'.$user.'_'.$visitor)];
	  //$statistics = false; //调试
	  if(!empty($statistics)){
	    return;
	  }
	  $date = time();
	  $ip = ip2long(self::getVisitorIp());
	  $source = self::urlSource();
	  //判断在CACHE中是否有数据
	  $cache = new UCLibCache('visitors');
	 	$key = self::_visitorKey($user,'visitors','homeIndex');
	 	$ret = $cache->read($key);
	 	//$ret = false; //调试
	 	if(!$ret){
	 		//将数据写入DB
	 		self::visitorDb($user,$visitor,$date);
	 		$list = array();
	 		$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	 		$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user=? ORDER BY date DESC LIMIT ?,?";
	 		$params = array($user,0,$num);
	 		$row = $pdo->query_with_prepare($sql,$params);
	 		if($row === false || !is_array($row)){
	 	  	return;
	 	  }
	 	  if($row == false){
	 	  	return false;
	 	  }
	 	  foreach($row as $visitKey=>$value){
	 	    $list[$value['visitors']] = array('user'=>$value['user'],'visitors'=>$value['visitors'],'date'=>$value['date'],'ip'=>$value['ip'],'source'=>$value['source']);
	 	  }
	 	  //将新的数据写入CACHE
	 	  $cache->write($key,serialize($list));
	 	  //读取总数
	 	  $pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	 	  $sql = "SELECT count(*) as total FROM $pdo->database.$pdo->table WHERE user=?";
	 	  $params = array($user);
	 	  $row = $pdo->query_one_row_with_prepare($sql,$params);
	 	  $total = $row['total'];
	 	  $key = self::_visitorKey($user,'visitors','myMoreTotal');
	 	  //将总数写入CACHE
	 	  $cache->write($key,$total);
	 		//删除更多信息的CACHE
	 		$key = self::_visitorKey($user,'visitors','myMore');
	 		$cache->delete($key);
  	  $cache->close();
  	  self::visitorCookie($user,$visitor);
  	  return;
	 	}
	 	$ret = unserialize($ret);
	 	//判断用户是否存在CACHE中，如果存在则删除否则总数加1
	 	if(array_key_exists($visitor,$ret)){
	 		unset($ret[$visitor]);
	 	}else{
	 		//总数加1
	 		$keytotal = self::_visitorKey($user,'visitors','myMoreTotal');
	 		$total = $cache->read($keytotal);
	 		$cache->write($keytotal,$total+1);
	 	}
	 	$new = array($visitor=>array('user'=>$user,'visitors'=>$visitor,'date'=>$date,'ip'=>$ip,'source'=>$source));
	 	$ret = $new+$ret;
	 	//判断数组是否大于$num
	 	if(count($ret) > $num){
	 	  $row = array();
	 	  $i = 0;
	 	  foreach($ret as $vistkey=>$value){
	 	    if($i<$num){
	 	      $row[$vistkey] = $value;
	 	    }else{
	 	      break;
	 	    }
	 	    $i++;
	 	  }
	 	}
	 	//将新的数据写入CACHE
	 	$cache->write($key,serialize($ret));
	 	//将数据写入DB
	 	self::visitorDb($user,$visitor,$date);
  	//删除更多信息的CACHE
	 	$key = self::_visitorKey($user,'visitors','myMore');
	 	$cache->delete($key);
  	$cache->close();
  	self::visitorCookie($user,$visitor);
  }
  
  /**
   * 读取全部访问用户的UID，已字符串存于CACHE中
   * $user = 被访问者user_id;
   * $visitor = 访问者
   * $type = visitors 谁开看过我
   * $type = browse 我去看过谁
  **/
  public static function accessRecords($user,$visitor,$type){
  	$user	= strtolower(trim($user));
	  $visitor	= strtolower(trim($visitor));
  	if($type != 'visitors' && $type != 'browse'){
  		return false;
  	}
  	if($user == $visitor){
  		return false;
  	}
  	if($type == 'visitors'){
  		$key = self::_visitorKey($user,'visitors','accessRecords');
  		//判断在CACHE中是否有数据
	  	$cache = new UCLibCache('visitors');
	 		$ret = $cache->read($key);
	 		if($ret === false || $ret == 'NULL'){
	 			$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	  		$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user=? and visitors=?";
	  		$params = array($user,$visitor);
	 			$row = $pdo->query_one_row_with_prepare($sql,$params);
	 			if($row === false){
	 				return false;
	 			}
	 			if(empty($row) || !is_array($row) || $row == 'NULL'){
	 				$ret = 'OFF';
	 			}else{
	 				$ret = 'ON';
	 			}
	 			$cache->write($key,$ret);
	 		}
	 		$cache->close();
  	}else{
  		//我去访问过谁
  		$key = self::_visitorKey($visitor,'browse','accessRecords');
  		$cache = new UCLibCache('visitors');
  		$ret = $cache->read($key);
  		if($ret === false){
  			$pdo = UCLibPDOFactory::getPDO('browse',$visitor,'commentdbconfig');
	 			$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user=? and browse=?";
	 			$params = array($visitor,$user);
	 			$row = $pdo->query_one_row_with_prepare($sql,$params);
	 			if($row === false){
	 	  		return false;
	 	  	}
	 	  	if(empty($row) || !is_array($row) || $row == 'NULL'){
	 	  		$ret = 'OFF';
	 	  	}else{
	 	  		$ret = 'ON';
	 	  	}
	 	  	$cache->write($key,$val);
	 	  }
	 	  $cache->close();
	 	}
	 	return $ret;
  }
  
  /***
  * 将用户访问记录置为ON
  * $user = 被访问者user_id;
  * $visitor = 访问者
  * $type = visitors 谁开看过我
  * $type = browse 我去看过谁
 	**/
 	public static function accessRecordsOk($user,$visitor){
 		$user	= strtolower(trim($user));
	  $visitor	= strtolower(trim($visitor));
  	if($user == $visitor){
  		return false;
  	}
  	$cache = new UCLibCache('visitors');
  	$key = self::_visitorKey($user,'visitors','accessRecords');
  	$cache->write($key,'ON');
  	$key = self::_visitorKey($visitor,'browse','accessRecords');
  	$cache->write($key,'ON');
  	$cache->close();
  }
  	
	
	/**
	 * 将用户访问数据写入DB
	 * @param $user:被访问用户的ID
	 * @param $visitor:访问用户的ID
	 * $int $date:访问时间
	 **/
	 public static function visitorDb($user,$visitor,$date){
	  $user	= strtolower(trim($user));
	  $visitor	= strtolower(trim($visitor));
	  if(!$user || !$visitor){
	    return;
	  }
	  $ip = ip2long(self::getVisitorIp());
	  $source = self::urlSource();
	  //处理谁来看过我的数据
	  $info = self::accessRecords($user,$visitor,'visitors');
	  if($info == 'OFF'){
	  	$visit_data = array('user'=>$user,'visitors'=>$visitor,'date'=>$date,'ip'=>$ip,'source'=>$source);
	  	$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	  	$pdo->insert($visit_data);
	  	self::accessRecordsOk($user,$visitor);
	  }elseif($info == 'ON'){
	  	$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	  	$pdo->update(array('date'=>$date,'ip'=>$ip,'source'=>$source),array('user'=>$user,'visitors'=>$visitor));
	  }else{
	  	return;
	  }
	  //处理我去看过谁
	  $info = self::accessRecords($user,$visitor,'browse');
	  if($info == 'OFF'){
	  	$browse_data = array('user'=>$visitor,'browse'=>$user,'date'=>$date,'ip'=>$ip,'source'=>$source);
	 		$pdo = UCLibPDOFactory::getPDO('browse',$visitor,'commentdbconfig');
	 		$pdo->insert($browse_data);
	 	}elseif($info == 'ON'){
	 		$pdo = UCLibPDOFactory::getPDO('browse',$visitor,'commentdbconfig');
	   	$pdo->update(array('date'=>$date,'ip'=>$ip,'source'=>$source),array('user'=>$visitor,'browse'=>$user));
	  }else{
	  	return;
	  }
	 }
	 
	 /**
	 * 将用户的访问标识写一个COOKIE
	 * 在用户关闭浏览器后COOKIE失效
	 * 在COOKIE有效期内只记录一次新的访问
	 * @param $user:被访问用户的ID
	 * @param $visitor:访问用户的ID
	 **/
	 public static function visitorCookie($user,$visitor){
	  $user	= strtolower(trim($user));
	  $visitor	= strtolower(trim($visitor));
	  if(!$user || !$visitor){
	    return;
	  }
	  $key = strtoupper('HOME_'.$user.'_'.$visitor);
	  $value = time();
	  //setcookie($key, $value, 0, "/", ".sdo.com");
	}
	
	/**
	 * 读取用户主页访问总数
	 * @param $user: 被访问用户ID
	 */
	 public static function totalVisitor($user){
	  $user	= strtolower(trim($user));
	  if(!$user){
	    return false;
	  }
	  $cache = new UCLibCache('visitors');
	 	$key = self::_visitorKey($user,'visitors','myMoreTotal');
	 	$total = $cache->read($key);
	 	if($total == null){
	 		$total = false;
	 	}
	 	if($total === false && $ret != 'error'){
	 		$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	 		$sql = "SELECT count(*) as total FROM $pdo->database.$pdo->table WHERE user=?";
	 		$params = array($user);
	 		$row = $pdo->query_one_row_with_prepare($sql,$params);
	 	  //CMDB::dsn('visitors', $user);
	 	  //$row = CMDB::getRows($sql);
	 	  //CMDB::close();
	 	  $total = $row['total'];
	 	  //将总数写入CACHE
	 	  $cache->write($key,$total);
	 	}
	 	return $total;
	}
	 	
	  
	  
	
	/**
	 * 读取用户主页访问数据
	 * @param $user: 被访问用户ID
	 */
	 
	 public static function readVisitor($user){
	  $user	= strtolower(trim($user));
	  $num=30;
	  if(!$user){
	    return false;
	  }
	 	$cache = new UCLibCache('visitors');
	 	$key = self::_visitorKey($user,'visitors','homeIndex');
	 	$ret = $cache->read($key);
	 	//$ret = false;
	 	if(empty($ret)){
	 		$pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	 	  $sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user=? and visitors<>? ORDER BY date DESC LIMIT ?,?";
	 	  $params = array($user,' ',0,$num);
	 	  $row = $pdo->query_with_prepare($sql,$params);
	 	  if($row === false || !is_array($row)){
	 	  	return;
	 	  }
	 	  //CMDB::dsn('visitors', $user);
	 	  //$row = CMDB::getRows($sql);
	 	  //CMDB::close();
	 	  $ret = array();
	 	  foreach($row as $visitKey=>$value){
	 	    $ret[$value['visitors']] = array('user'=>$value['user'],'visitors'=>$value['visitors'],'date'=>$value['date'],'ip'=>$value['ip'],'source'=>$value['source']);
	 	  }
	 	  //将新的数据写入CACHE
	 	  $cache->write($key,serialize($ret));
	 		return $ret;
	 	}else{
	 		return unserialize($ret);
	 	}
	}
	
	/**
	 * 读取用户更多访问数据
	 * 每页50条记录
	 * @param $user: 被访问用户ID
	 * @int $page: 页码
	 **/
	 public static function moreVisitor($user,$page=0){
	  $user	= strtolower(trim($user));
	  $page_size = 50;
	  if(!$user){
	    return false;
	  }
	  $page = intval($page);
	  if(empty($page) || $page < 0){
	    $page = 1;
	  }
	  $ret = false;
	  if($page == 1){
	    $cache = new UCLibCache('visitors');
	 	  $key = self::_visitorKey($user,'visitors','myMore');
	 	  $ret = $cache->read($key);
	 	}
	 	if($ret === false && $ret != 'error'){
	 	  $pagecount = ceil($total/$page_size);
	 	  if($page > $pagecount){
	 	    $page = $pagecount;
	 	  }
	 	  if($page == 0){
	 	    $page = 1;
	 	  }
	 	  $total = self::totalVisitor($user);
	 	  $pdo = UCLibPDOFactory::getPDO('visitors',$user,'commentdbconfig');
	 	  $sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user=? ORDER BY date DESC LIMIT ?,?";
	 	  $params = array($user,(($page-1)*$page_size),$page_size);
	 	  $ret = $pdo->query_one_row_with_prepare($sql,$params);
	 	  if($ret === false || !is_array($ret)){
	 	  	return;
	 	  }
	 	  //$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user='".$user."' ORDER BY date DESC";
	 	  //CMDB::dsn('visitors',$user);
			//$ret = CMDB::getPage($sql, $page, $total, $page_size);
			//CMDB::close();
			if(!$ret && $page==1){
			  $cache->write($key,'error');
  			$cache->close();
  			return false;
  		}elseif(!empty($ret) && $page==1){
  		  $cache->write($key,$ret);
  		}
  	}else{
  	  return false;
  	}
  	return $ret;
  }
 	
	//获取用户的IP地址
  public static function getVisitorIp(){
  	if (isset($_SERVER)) {
  		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  			return $_SERVER['HTTP_X_FORWARDED_FOR'];
  		} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  			return $_SERVER['HTTP_CLIENT_IP'];
  		} else {
  			return $_SERVER['REMOTE_ADDR'];
  		}
  	} else {
  		if (getenv("HTTP_X_FORWARDED_FOR")) {
  			return getenv( "HTTP_X_FORWARDED_FOR");
  		} elseif (getenv("HTTP_CLIENT_IP")) {
  			return getenv("HTTP_CLIENT_IP");
  		} else {
  			return getenv("REMOTE_ADDR");
			}
		}
		return false;
	}
	
	protected function urlSource(){
	  return $_SERVER['HTTP_REFERER'];
	}
}
?>